package RSA;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author WuYongheng
 * @date 2022/11/21
 * @description
 */
public class RsaUtils {

    public static void main(String[] args) throws Exception {
        System.out.println();
        // 生成公私钥对
        RsaKeyPair keyPair = generateKeyPair();
        System.out.println("公钥：" + keyPair.getPublicKey());
        System.out.println("私钥：" + keyPair.getPrivateKey());
        System.out.println();
        test1(keyPair);
        System.out.println("\n");
        test2(keyPair);
        System.out.println("\n");
    }

    /**
     * 静态的，跑程序时会优先加载，去调用ReadData()方法
     * 使用 final 关键字，保证读取到的数据不可更改
     */
    private static final String SRC;

    static {
        try {
            SRC = ReadData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用缓存流读取 aaa.txt 文件中的内容
     *
     * @return 文件内容
     * @throws IOException
     */
    public static String ReadData() throws IOException {
        String fileName = "D:\\code\\aaa.txt";
        final StringBuilder myData = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("文件内容是: " + line);
                myData.append(line);
            }
        }
        return myData.toString();
    }

    /**
     * 公钥加密私钥解密
     *
     * @param keyPair
     * @throws Exception
     */
    private static void test1(RsaKeyPair keyPair) throws Exception {
        System.out.println("***************** 公钥加密私钥解密开始 *****************");
        // 用公钥加密得到 text1
        String text1 = encryptByPublicKey(keyPair.getPublicKey(), RsaUtils.SRC);
        // 用私钥解密 text1 得到 text2
        String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), text1);
        System.out.println("加密前：" + RsaUtils.SRC);
        System.out.println("加密后：" + text1);
        System.out.println("解密后：" + text2);
        if (RsaUtils.SRC.equals(text2)) {
            System.out.println("解密字符串和原始字符串一致，解密成功");
        } else {
            System.out.println("解密字符串和原始字符串不一致，解密失败");
        }
        System.out.println("***************** 公钥加密私钥解密结束 *****************");
    }

    /**
     * 私钥加密公钥解密
     * 过程与 test1类似
     *
     * @param keyPair
     * @throws Exception
     */
    private static void test2(RsaKeyPair keyPair) throws Exception {
        System.out.println("***************** 私钥加密公钥解密开始 *****************");
        String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), RsaUtils.SRC);
        String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1);
        System.out.println("加密前：" + RsaUtils.SRC);
        System.out.println("加密后：" + text1);
        System.out.println("解密后：" + text2);
        if (RsaUtils.SRC.equals(text2)) {
            System.out.println("解密字符串和原始字符串一致，解密成功");
        } else {
            System.out.println("解密字符串和原始字符串不一致，解密失败");
        }
        System.out.println("***************** 私钥加密公钥解密结束 *****************");
    }

    /**
     * 公钥加密方法
     *
     * @param publicKeyText 公钥
     * @param text          将要加密的信息
     * @return Base64编码的字符串
     * @throws Exception
     */

    public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
        // 返回按照 X.509 标准进行编码的密钥的字节
        // x509EncodedKeySpec2 是一种规范、规格
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        // 让密钥工厂按照指定的 规范 生成公钥
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        // 对加密初始化，使用加密模式，公钥加密
        // Cipher.ENCRYPT_MODE 可以用 1 代替
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] result = cipher.doFinal(text.getBytes());
        // 返回 Base64编码的字符串
        return Base64.encodeBase64String(result);
    }

    /**
     * 公钥解密方法
     * 过程与encryptByPublicKey()方法类似
     *
     * @param publicKeyText 公钥
     * @param text          待解密的信息
     * @return 字符串
     * @throws Exception
     */

    public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 私钥加密方法
     * 过程与encryptByPublicKey()方法类似
     *
     * @param privateKeyText 私钥
     * @param text           将要加密的信息
     * @return Base64编码的字符串
     * @throws Exception
     */
    public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

    /**
     * 私钥解密方法
     * 过程与encryptByPublicKey()方法类似
     *
     * @param privateKeyText 私钥
     * @param text           待解密的信息
     * @return 字符串
     * @throws Exception
     */

    public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }


    /**
     * 创建RSA公私钥对
     *
     * @return new RsaKeyPair(publicKeyString, privateKeyString)
     * @throws NoSuchAlgorithmException
     */
    public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        // 创建公私钥对，指定算法 - RSA
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 设置密钥大小 1024 bits， >=512
        keyPairGenerator.initialize(1024);
        // 创建KeyPair对象，用于接收公私钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 生成随机的公私钥对
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 把密钥转换成 Base64编码的字符串
        String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
        String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
        return new RsaKeyPair(publicKeyString, privateKeyString);
    }


    /**
     * RSA密钥对 对象
     */
    public static class RsaKeyPair {
//        private final String publicKey;
//        private final String privateKey;

        // 也可以将密钥写死
        private final String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJjHLLUsURM6KFIpLZWKsF7ApA8rmcCA3g7yjh1VV+uzbulBMtisRUZDlGqqEVF8dQ+0sIs2xg4qO4OMZ6vGyaUCAwEAAQ==";
        private final String privateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAmMcstSxREzooUiktlYqwXsCkDyuZwIDeDvKOHVVX67Nu6UEy2KxFRkOUaqoRUXx1D7SwizbGDio7g4xnq8bJpQIDAQABAkB9QGVNzxxU2Awwd6Pwgrhfpi2aZlNx9/SVapPKRqqDB9n5D0JwDKmDXkSmoaLkN95NiiM/SZK6JDgwGp5NlmIhAiEA65Zp+tId4dVrGG2lFvYk2HsDPmuYvi6WFC/sb6B3URkCIQCmA/S8/v1NVmJBEHtPdEWkQ6diRPzBuYiB2n+yLKGSbQIgSGImndIBLGoORasqlit6lqj1DjCw9X4KzpkK5CFBh8ECIQCYwmsgvUE3OJWQaSoOIl8yl04eDnzFhYMmeXem64qAwQIgODpavuG5vOWu8+AnGJPoabOQCtu2nFxFSxSCO8KWvz4=";
        public RsaKeyPair(String publicKey, String privateKey) {
//            this.publicKey = publicKey;
//            this.privateKey = privateKey;
            publicKey = this.publicKey;
            privateKey = this.privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

    }
}
